using AspectCore.Extensions.DependencyInjection;
using LdtCommonLogger;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;

namespace ClassifyApp.Webapi
{
    /// <summary>
    /// Program
    /// </summary>
#pragma warning disable S1118 // Utility classes should not have public constructors
    public class Program
#pragma warning restore S1118 // Utility classes should not have public constructors
    {
#pragma warning disable CS0618 // 类型或成员已过时
        private static NLog.Logger logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
#pragma warning restore CS0618 // 类型或成员已过时
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("zh-CN", true)
            {
                DateTimeFormat = {
                    ShortDatePattern = "yyyy-MM-dd",
                    FullDateTimePattern = "yyyy-MM-dd HH:mm:ss",
                    LongTimePattern = "HH:mm:ss",
                    LongDatePattern="yyyy-MM-dd HH:mm:ss",
                    ShortTimePattern="HH:mm:ss"
                }
            };
            try
            {
                var versionInfo = FileVersionInfo.GetVersionInfo(Path.Combine(AppContext.BaseDirectory, $"{nameof(ClassifyApp)}.{nameof(ClassifyApp.Webapi)}.dll"));
                LoggerExtend.SetVersion(versionInfo.FileVersion);
                var t = CreateHostBuilder(args).Build();
                //var www = t.Services.GetService(typeof(ISettingCenter));//读取依赖注入得类得方法
                t.Run();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }
        private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = (e.ExceptionObject as Exception);
            logger.Error(ex, "UnhandledException");
        }
        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs ex)
        {
            logger.Error(ex.Exception, "UnhandledException");
            ex.SetObserved();
        }
        /// <summary>
        /// Creates the host builder.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
              .ConfigureAppConfiguration((hostingContext, config) =>
              {
                  //重新指定配置文件基础目录
                  config.SetBasePath(AppContext.BaseDirectory);
              })
              .ConfigureWebHostDefaults(webBuilder =>
              {
                  //重新指定静态文件路径地址
                  webBuilder.UseWebRoot(Path.Combine(System.AppContext.BaseDirectory, "wwwroot"));
                  webBuilder.UseStartup<Startup>().ConfigureKestrel(opt =>
                  {
                      opt.Limits.MinRequestBodyDataRate = null;
                      //opt.Limits.MaxRequestBodySize = int.MaxValue;//限制请求长度
                  }
                  );
              })
              .ConfigureLogging(logging =>
              {
                  logging.ClearProviders();
                  logging.SetMinimumLevel(LogLevel.Debug);
              })
            .UseServiceProviderFactory(new DynamicProxyServiceProviderFactory())
            .UseNLog();
    }
}
